#!/bin/bash

# 获取当前日期和时间
timestamp=$(date +"%Y-%m-%d %H:%M:%S")

version="v1.0.0"
projectName="yunfan"
baseOutputDir="$projectName-$version"

#architectures=("amd64" "arm64")
architectures=("amd64")

package_for_arch() {
    local arch=$1
    local outputDir="$baseOutputDir-linux-$arch"
    local binDir="$outputDir/bin"
    local configDir="$outputDir/etc"
    local logsDir="$outputDir/logs"
    local tmpDir="$outputDir/tmp"
    local packageDir="$outputDir/package"
    local dependencyDir="$outputDir/dependency"
    local tarGzFileName="$outputDir.tar.gz"

    # 删除现有目录（如果存在）
    if [ -d "$outputDir" ]; then
        echo -e "\033[31m[$timestamp] Delete path $outputDir \033[1m"
        rm -rf "$outputDir"
    fi

    if [ -f "$tarGzFileName" ]; then
        echo -e "\033[31m[$timestamp] Delete file $tarGzFileName \033[1m"
        rm -f "$tarGzFileName"
    fi

    # 创建输出目录结构
    echo -e "\033[32m[$timestamp] Create dir $outputDir \033[1m"
    mkdir -p "$binDir" "$configDir" "$logsDir" "$tmpDir" "$packageDir" "$dependencyDir"

    # 设置Go环境变量
    export CGO_ENABLED=0
    export GOOS=linux
    export GOARCH=$arch

    # 编译项目
    echo -e "\033[33m[$timestamp] Compiling projects for $arch... \033[1m"
    go build -ldflags="-s -w" -tags no_k8s -o "$binDir/api-server" ../api-server/api_server_main.go
    go build -ldflags="-s -w" -tags no_k8s -o "$binDir/agent-server" ../rpc-server/agent_server_main.go
    go build -ldflags="-s -w" -tags no_k8s -o "$binDir/alert-server" ../alert-server/alert_server_main.go
    go build -ldflags="-s -w" -tags no_k8s -o "$binDir/log-server" ../log-server/log_server_main.go

    # 复制配置文件
    echo -e "\033[34m[$timestamp] Copying start.sh for $arch... \033[1m"
    cp -r ./service_manager.sh "$binDir"

    # 复制配置文件
    echo -e "\033[34m[$timestamp] Copying configuration files for $arch... \033[1m"
    cp -r ../etc/* "$configDir"

    # 复制 package 目录中的文件到 packageDir
    echo -e "\033[35m[$timestamp] Copying scripts and packages for $arch... \033[1m"
#    cp ./package/jdk* "$packageDir"
#    cp ./package/kafka* "$packageDir"
#    cp ./package/apache* "$packageDir"
    cp ./package/node* "$packageDir"
    cp ./dependencies/centos/* "$dependencyDir"
    cp ./dependencies/ubuntu/* "$dependencyDir"
    cp ./service_file/*.service "$tmpDir"
#    cp ./package/open* "$packageDir"

    chmod -R +x $binDir

    echo -e "\033[36m[$timestamp] The build for $arch is complete. \033[1m"

    echo -e "\033[32m[$timestamp] Packaging project for $arch into tar.gz... \033[1m"
    tar -czf "$tarGzFileName" "$outputDir"

    echo -e "\033[32m[$timestamp] Project for $arch has been packaged into $tarGzFileName \033[1m"
}

for arch in "${architectures[@]}"; do
    package_for_arch $arch
done
